﻿using IOA.MES.Business;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace IOA.MES.Web.Controllers
{
    public class ParaSettingController : Controller
    {
        #region 组件过站配置

        /// <summary>
        /// 组件过站配置页面
        /// </summary>
        public ActionResult CompCrossSiteMgr(string orderNo, string workOrderNo = "")
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            ViewBag.Sites = new ParaSettingsMgr().QuerySiteTypes();
            ViewBag.Config = new ViaSiteConfigMgr().GetConfig(orderNo, workOrderNo);
            return View();
        }

        /// <summary>
        /// 编辑组件过站配置
        /// </summary>
        [HttpPost]
        public JsonResult EditViaSiteConfig(VViaSiteConfig model)
        {
            model.CreateBy = BaseEnv.UserId;
            new ViaSiteConfigMgr().EditViaSites(model);
            return Json(new ResultJson<object>());
        }

        #endregion

        #region QTime配置

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult QTimeMgr(string orderNo = "", string workOrderNo = "")
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            var config = new ViaSiteConfigMgr().GetConfig(orderNo, workOrderNo);
            return View(config);
        }

        /// <summary>
        /// 编辑QTime接口
        /// </summary>
        [HttpPost]
        public JsonResult EditQTime(VViaSiteConfig model)
        {
            model.CreateBy = BaseEnv.UserId;
            new ViaSiteConfigMgr().EditQTime(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 产线绑定
        /// <summary>
        /// 产线绑定页面
        /// </summary>
        /// <returns></returns>
        public ActionResult BindLine(string workOrderNo)
        {
            ViewBag.WorkOrderNo = workOrderNo;
            var workOrder = new WorkOrderMgr().GetWorkOrder(workOrderNo);
            var total = 0;
            ViewBag.Lines = new AssemblyLineMgr().QueryLines(1, 0, out total, workOrder.WorkshopCode, CommonStatus.Normal);
            return View(workOrder);
        }

        /// <summary>
        /// 保存产线绑定
        /// </summary>
        [HttpPost]
        public JsonResult SaveBindLine(string workOrderNo, List<int> lineIds)
        {
            new PackConditionMgr().BindLine(new VWorkOrder
            {
                WorkOrderNo = workOrderNo,
                LineId = string.Join(",", lineIds ?? new List<int>()),
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 包装条件配置
        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult PackConditionMgr(string orderNo, string workOrderNo, QLevelCondition qLevelCondition)
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            ViewBag.QLevelCondition = (int)qLevelCondition;

            var condition = new PackConditionMgr().GetPackCondition(orderNo, workOrderNo, qLevelCondition);
            return View(condition);
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditPackCondition(VPackCondition model)
        {
            model.CreateBy = BaseEnv.UserId;
            new PackConditionMgr().Edit(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 拼柜条件配置

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult CabinetConditionMgr(string orderNo, string workOrderNo, QLevelCondition qLevelCondition)
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            ViewBag.QLevelCondition = (int)qLevelCondition;

            var condition = new CabinetConditionMgr().GetCabinetCondition(orderNo, workOrderNo, qLevelCondition);
            return View(condition);
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditCabinetCondition(VCabinetCondition model)
        {
            model.CreateBy = BaseEnv.UserId;
            new CabinetConditionMgr().Edit(model);
            return Json(new ResultJson<object>());
        }

        #endregion

        #region IV上传配置
        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult IVUploadMgr(string orderNo = "", string workOrderNo = "")
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            var config = new ViaSiteConfigMgr().GetConfig(orderNo, workOrderNo);
            return View(config);
        }

        /// <summary>
        /// 编辑IV上传配置
        /// </summary>
        [HttpPost]
        public JsonResult EditIVUpload(VViaSiteConfig model)
        {
            model.CreateBy = BaseEnv.UserId;
            new ViaSiteConfigMgr().EditIVUpload(model);
            return Json(new ResultJson<object>());
        }

        #endregion

        #region IV温度配置
        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult IVTempMgr()
        {
            var config = new ViaSiteConfigMgr().GetIVTemp();
            return View(config);
        }

        /// <summary>
        /// 编辑IV温度配置
        /// </summary>
        [HttpPost]
        public JsonResult SaveIVTemp(VIVTemp model)
        {
            model.CreateBy = BaseEnv.UserId;
            new ViaSiteConfigMgr().SaveIVTemp(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 设备参数配置

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult DeviceParamMgr()
        {
            ViewBag.DeviceTypes = new List<string>() { "焊接机", "层压机" };
            ViewBag.DeviceNos = new List<string>() { "焊接机001", "层压机002" };
            ViewBag.ParamNames = new List<string>() { "1#预热", "温度" };
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <returns></returns>
        public ActionResult DeviceParamEdit(int? pkId, string OrderNo)
        {
            VDeviceParam v = null;
            if (pkId.Value <= 0)
            {
                v = new VDeviceParam();
            }
            else
            {
                v = new DeviceParamMgr().Get(pkId.Value, OrderNo);
            }

            ViewBag.DeviceTypes = new List<string>() { "焊接机", "层压机" };
            ViewBag.DeviceNos = new List<string>() { "焊接机001", "层压机002" };
            ViewBag.ParamNames = new List<string>() { "1#预热", "温度" };

            return View(v);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryDeviceParams(int page, int limit, string deviceType, string deviceNo, string paramName)
        {
            var total = 0;
            var models = new DeviceParamMgr().Query(page, limit, out total, deviceType, deviceNo, paramName);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditDeviceParamMgr(VDeviceParam model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new DeviceParamMgr().Edit(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public JsonResult DeviceParamDelete(int pkId)
        {
            new DeviceParamMgr().Delete(new VDeviceParam { PkId = pkId, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 分档方案
        /// <summary>
        /// 分档方案管理
        /// </summary>
        public ActionResult BinningSchemeMgr()
        {
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View();
        }

        /// <summary>
        /// 编辑分档方案
        /// </summary>
        public ActionResult EditBinningScheme(int schemaId = 0)
        {
            var schema = schemaId <= 0 ? null : new BinningSchemeMgr().GetBinningSchema(schemaId);
            ViewBag.Workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            return View(schema);
        }

        /// <summary>
        /// 查询分档方案列表
        /// </summary>
        [HttpPost]
        public JsonResult SaveBinningSchema(VBinningSchema model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new BinningSchemeMgr().EditSchema(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除分档规则
        /// </summary>
        [HttpPost]
        public JsonResult DeleteBinningSchema(int schemaId)
        {
            new BinningSchemeMgr().Delete(new VBinningSchema
            {
                PkId = schemaId,
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询分档方案列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryBinningSchemas(int page, int limit, string workshopCode, string key)
        {
            var total = 0;
            var schemas = new BinningSchemeMgr().Query(page, limit, out total, workshopCode, key);
            return Json(new ResultJson<object>(schemas, total));
        }

        /// <summary>
        /// 分档规则详情
        /// </summary>
        public ActionResult BinningSchemaDetail(int schemaId)
        {
            var powers = new BinningSchemeMgr().QueryBinningPowers(schemaId);
            ViewBag.Powers = powers;
            var schema = new BinningSchemeMgr().GetBinningSchema(schemaId);
            return View(schema);
        }

        /// <summary>
        /// 查询功率档列表
        /// </summary>
        /// <param name="schemaId">分档规则ID</param>
        [HttpPost]
        public JsonResult QueryBinningPowers(int schemaId)
        {
            var powers = schemaId <= 0 ? new List<VBinningPower>() : new BinningSchemeMgr().QueryBinningPowers(schemaId);
            return Json(new ResultJson<object>(powers, powers.Count));
        }

        /// <summary>
        /// 编辑功率档页面
        /// </summary>
        public ActionResult EditBinningPower(int schemaId, int powerId = 0)
        {
            ViewBag.SchemaId = schemaId;
            var power = powerId < 0 ? null : new BinningSchemeMgr().GetBinningPower(powerId);
            return View(power);
        }

        /// <summary>
        /// 编辑功率档
        /// </summary>
        [HttpPost]
        public JsonResult SaveBinningPower(VBinningPower model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new BinningSchemeMgr().EditPower(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除功率档
        /// </summary>
        [HttpPost]
        public JsonResult DeleteBinningPower(int powerId)
        {
            new BinningSchemeMgr().DeletePower(new VBinningPower
            {
                PkId = powerId,
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询电流档列表
        /// </summary>
        /// <param name="schemaId">分档规则ID</param>
        [HttpPost]
        public JsonResult QueryBinningCurrents(int powerId)
        {
            var currents = new BinningSchemeMgr().QueryBinningCurrents(powerId);
            return Json(new ResultJson<object>(currents, currents.Count));
        }

        /// <summary>
        /// 编辑电流档页面
        /// </summary>
        public ActionResult EditBinningCurrent(int powerId, int currentId = 0)
        {
            ViewBag.PowerId = powerId;
            var power = currentId <= 0 ? null : new BinningSchemeMgr().GetBinningCurrent(currentId);
            return View(power);
        }

        /// <summary>
        /// 编辑电流档
        /// </summary>
        [HttpPost]
        public JsonResult SaveBinningCurrent(VBinningCurrent model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new BinningSchemeMgr().EditCurrent(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除电流档
        /// </summary>
        [HttpPost]
        public JsonResult DeleteBinningCurrent(int currentId)
        {
            new BinningSchemeMgr().DeleteCurrent(new VBinningCurrent
            {
                PkId = currentId,
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 工单分档规则
        /// </summary>
        public ActionResult WorkOrderBinningSchemaMgr(string orderNo, string workOrderNo)
        {
            var total = 0;
            var workOrder = new WorkOrderMgr().GetWorkOrder(workOrderNo);
            ViewBag.Schemas = new BinningSchemeMgr().Query(1, 0, out total, workOrder.WorkshopCode, "");
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            var workOrderBinningSchema = new BinningSchemeMgr().GetWorkorderBinningSchema(orderNo, workOrderNo);
            return View(workOrderBinningSchema);
        }

        /// <summary>
        /// 保存工单分档
        /// </summary>
        [HttpPost]
        public JsonResult SaveWorkOrderBinningSchema(VWorkOrderBinningSchema model)
        {
            model.CreateBy = BaseEnv.UserId;
            new BinningSchemeMgr().SaveWorkorderBinningSchema(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 标签设置
        /// <summary>
        /// 页面配置
        /// </summary>
        public ActionResult LableMgr(string orderNo = "", string workOrderNo = "")
        {
            var total = 0;
            ViewBag.Templates = new LabelMgr().QueryTemplates(1, 0, out total, "");
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            var label = new LabelMgr().GetWorkOrderLabel(orderNo, workOrderNo);
            return View(label);
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditLable(VWorkorderLable model)
        {
            model.CreateBy = BaseEnv.UserId;
            new LabelMgr().Edit(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 标签模板管理
        /// </summary>
        public ActionResult LabelTemplateMgr()
        {
            return View();
        }

        /// <summary>
        /// 标签模板管理
        /// </summary>
        public ActionResult EditLabelTemplate(int templateId = 0)
        {
            var model = templateId <= 0 ? null : new LabelMgr().GetTemplate(templateId);
            return View(model);
        }

        /// <summary>
        /// 保存模板
        /// </summary>
        [HttpPost]
        public JsonResult GetLabelTemplate(int templateId)
        {
            var model = new LabelMgr().GetTemplate(templateId);
            return Json(new ResultJson<object>(model));
        }

        /// <summary>
        /// 保存模板
        /// </summary>
        [HttpPost]
        public JsonResult SaveLabelTemplate(VLabelTemplate model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new LabelMgr().SaveTemplate(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询模板列表
        /// </summary>
        public JsonResult QueryLabelTemplates(int page, int limit, string name)
        {
            var total = 0;
            var templates = new LabelMgr().QueryTemplates(page, limit, out total, name);
            return Json(new ResultJson<object>(templates, total));
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        [HttpPost]
        public JsonResult RemoveTemplate(int templateId)
        {
            new LabelMgr().DeleteTemplate(new VLabelTemplate
            {
                PkId = templateId,
                ModifyBy = BaseEnv.UserId,
            });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 不良原因配置
        /// <summary>
        /// 不良分类管理
        /// </summary>
        public ActionResult BadTypeMgr()
        {
            return View();
        }

        /// <summary>
        /// 查询不良大类列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryBadType(int page, int limit, string key)
        {
            var total = 0;
            var models = new BadReasonMgr().QueryTypes(page, limit, out total, key);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        public ActionResult BadTypeEdit(int pkId = 0)
        {
            VBadType model = null;
            if (pkId <= 0)
            {
                model = new VBadType();
            }
            else
            {
                model = new BadReasonMgr().GetBadType(pkId);
            }

            return View(model);
        }

        /// <summary>
        /// 编辑大类接口
        /// </summary>
        [HttpPost]
        public JsonResult EditBadType(VBadType model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new BadReasonMgr().EditType(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 编辑大类接口
        /// </summary>
        [HttpPost]
        public JsonResult DeleteBadType(int pkId)
        {
            new BadReasonMgr().DeleteType(new VBadType
            {
                PkId = pkId,
                ModifyBy = BaseEnv.UserId
            });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult BadReasonMgr()
        {
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <returns></returns>
        public ActionResult BadReasonEdit(int? pkId)
        {
            VBadReason model = null;
            if (pkId.Value <= 0)
            {
                model = new VBadReason();
            }
            else
            {
                model = new BadReasonMgr().GetReason(pkId.Value);
            }

            var total = 0;
            ViewBag.BadTypes = new BadReasonMgr().QueryTypes(1, 0, out total, "");
            return View(model);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryBadReasons(int page, int limit, string type, string reason)
        {
            var total = 0;
            var models = new BadReasonMgr().QueryReasons(page, limit, out total, type, reason);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditBadReason(VBadReason model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new BadReasonMgr().EditReason(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public JsonResult BadReasonDelete(int pkId)
        {
            new BadReasonMgr().DeleteReason(new VBadReason { PkId = pkId, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 等级颜色配置

        /// <summary>
        /// 页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RankColorSetMgr()
        {
            return View();
        }

        #region 等级颜色配置-等级

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RankSetMgr()
        {
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RankSetEdit(int? pkId)
        {
            VRankSet v = null;
            if (pkId.Value <= 0)
            {
                v = new VRankSet();
            }
            else
            {
                v = new LevelColorMgr().GetRank(pkId.Value);
            }

            return View(v);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryRankSets(int page, int limit, string elRank, string outRank, string finalRank)
        {
            var total = 0;
            var models = new LevelColorMgr().QueryRank(page, limit, out total, elRank, outRank, finalRank);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditRankSetMgr(VRankSet model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new LevelColorMgr().EditRank(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public JsonResult RankSetDelete(int pkId)
        {
            new LevelColorMgr().DeleteRank(new VRankSet { PkId = pkId, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 等级颜色配置-颜色

        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ColorSetMgr()
        {
            return View();
        }

        /// <summary>
        /// 编辑页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ColorSetEdit(int? pkId)
        {
            VColorSet v = null;
            if (pkId.Value <= 0)
            {
                v = new VColorSet();
            }
            else
            {
                v = new LevelColorMgr().GetColor(pkId.Value);
            }

            return View(v);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryColorSets(int page, int limit, string compColor, string compColorCode)
        {
            var total = 0;
            var models = new LevelColorMgr().QueryColor(page, limit, out total, compColor, compColorCode);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditColorSetMgr(VColorSet model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new LevelColorMgr().EditColor(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public JsonResult ColorSetDelete(int pkId)
        {
            new LevelColorMgr().DeleteColor(new VColorSet { PkId = pkId, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }
        #endregion

        #endregion

        #region IV本地数据格式配置
        /// <summary>
        /// 配置页面
        /// </summary>
        /// <returns></returns>
        public ActionResult IVLocalDataMgr()
        {
            var total = 0;
            ViewBag.Workshops = new WorkshopMgr().QueryWorkshops(1, 0, out total, null, string.Empty);
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryIVLocalDatas(string workshopCode = "")
        {
            var models = new IVLocalDataMgr().Query(workshopCode);
            return Json(new ResultJson<object>(models, models.Count));
        }

        /// <summary>
        /// 编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditIVLocalDataMgr(VIVLocalData model)
        {
            model.ModifyBy = BaseEnv.UserId;
            new IVLocalDataMgr().Edit(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 成品组件过站BOM
        /// <summary>
        /// 全局BOM配置
        /// </summary>
        /// <returns></returns>
        public ActionResult GlobalBomMgr(string orderNo, string workOrderNo)
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            ViewBag.Sites = new ParaSettingsMgr().QuerySiteTypes();
            return View();
        }

        /// <summary>
        /// 全局BOM配置
        /// </summary>
        /// <returns></returns>
        public ActionResult GlobalBomEdit(SiteType siteType, string orderNo, string workOrderNo)
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            ViewBag.SiteType = siteType;
            return View();
        }

        /// <summary>
        /// 查询全局BOM列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryGlobalSiteBoms(SiteType siteType, string orderNo, string workOrderNo)
        {
            var models = new ProductSiteBomMgr().QueryGlobalBoms(siteType, orderNo, workOrderNo);
            return Json(new ResultJson<object>(models, models.Count));
        }

        /// <summary>
        /// 保存全局BOM列表
        /// </summary>
        [HttpPost]
        public JsonResult EditGlobalSiteBom(SiteType siteType, string orderNo, string workOrderNo, List<string> categoryCodes)
        {
            new ProductSiteBomMgr().EditGlobalBom(siteType, orderNo, workOrderNo, categoryCodes, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryProductSiteBom(int page, int limit, string orderNo, string workOrderNo, SiteType siteType)
        {
            var total = 0;
            var models = new ProductSiteBomMgr().Query(page, limit, out total, orderNo, workOrderNo, siteType);
            return Json(new ResultJson<object>(models, total));
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public JsonResult ProductSiteBomDelete(int pkId)
        {
            new ProductSiteBomMgr().Delete(new VProductSiteBom { PkId = pkId, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 标片管理
        /// <summary>
        /// 标片管理
        /// </summary>
        public ActionResult StandardPieceMgr()
        {
            return View();
        }

        /// <summary>
        /// 标片编辑页
        /// </summary>
        public ActionResult EditStandardPiece(int pieceId = 0)
        {
            var piece = pieceId <= 0 ? null : new StandardPieceMgr().GetStandardPiece(pieceId);
            return View(piece);
        }

        /// <summary>
        /// 标片编辑接口
        /// </summary>
        [HttpPost]
        public JsonResult EditStandardPiece(VStandardPiece model)
        {
            if (model.PkId <= 0)
            {
                model.CreateBy = BaseEnv.UserId;
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
            }
            new StandardPieceMgr().EditStandardPiece(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 修改标片状态
        /// </summary>
        [HttpPost]
        public JsonResult ModifyStandardPieceStatus(int pieceId, CommonStatus status)
        {
            new StandardPieceMgr().ModifyStatus(new VStandardPiece { PkId = pieceId, Status = status, ModifyBy = BaseEnv.UserId });
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 查询标片列表
        /// </summary>
        [HttpPost]
        public JsonResult QueryStandardPieces(int page, int limit, string code, CommonStatus? status)
        {
            var total = 0;
            var machines = new StandardPieceMgr().QueryPieces(page, limit, out total, code, status);
            return Json(new ResultJson<object>(machines, total));
        }

        /// <summary>
        /// 编辑电池参数
        /// </summary>
        public ActionResult EditCellParas()
        {
            var paras = new CellParaMgr().QueryParas(null);
            ViewBag.CellLevelParas = paras.Where(_ => _.ParaType == ParaType.CellLevel).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.CellModelParas = paras.Where(_ => _.ParaType == ParaType.CellModel).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.CellEfficiencyParas = paras.Where(_ => _.ParaType == ParaType.CellEfficiency).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.OutputPowerParas = paras.Where(_ => _.ParaType == ParaType.OutputPower).OrderBy(_ => _.ParaValue).ToList();
            ViewBag.CellAreas = paras.Where(_ => _.ParaType == ParaType.CellArea).OrderBy(_ => _.ParaValue).ToList();
            return View();
        }

        /// <summary>
        /// 查询标片列表
        /// </summary>
        [HttpPost]
        public JsonResult SaveCellParas(ParaType type, List<VCellPara> paras)
        {
            paras = paras.Where(_ => !string.IsNullOrWhiteSpace(_.ParaValue)).ToList();
            new CellParaMgr().SaveParas(type, paras, BaseEnv.UserId);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 标片绑定
        /// </summary>
        public ActionResult StandardPieceBind(string orderNo, string workOrderNo)
        {
            var total = 0;
            ViewBag.WordOrderStandPieces = new WorkOrderMgr().QueryWorkOrderStandardPieces(orderNo, workOrderNo);
            ViewBag.StandardPieces = new StandardPieceMgr().QueryPieces(1, 0, out total, "", CommonStatus.Normal);
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            return View(new WorkOrderMgr().GetStandardPiece(orderNo, workOrderNo));
        }

        /// <summary>
        /// 绑定标片接口
        /// </summary>
        [HttpPost]
        public JsonResult SaveStandardPiece(string orderNo, string workOrderNo, List<string> productCodes, decimal? frequency)
        {
            new WorkOrderMgr().SaveStandardPiece(orderNo, workOrderNo, productCodes, frequency, BaseEnv.UserId);
            return Json(new ResultJson<dynamic>());
        }
        #endregion

        #region 等级配置

        /// <summary>
        /// 等级列表
        /// </summary>
        public ActionResult LevelIndex()
        {
            return View();
        }

        /// <summary>
        /// 查询等级分页
        /// </summary>
        [HttpPost]
        public JsonResult QueryLevels(int page, int limit)
        {
            var result = new LevelColorMgr().QueryLevels(page, limit);
            return Json(new ResultJson<List<VQLevel>>(result.Item1, result.Item2));
        }

        /// <summary>
        /// 编辑等级
        /// </summary>
        public JsonResult SaveLevel(QLevel model)
        {
            if (model.PkId == 0)
            {
                model.CreateBy = BaseEnv.UserId;
                model.CreateTime = DateTime.Now;

                new LevelColorMgr().AddLevel(model);
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
                model.ModifyTime = DateTime.Now;

                new LevelColorMgr().EditLevel(model);
            }

            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除等级
        /// </summary>
        [HttpPost]
        public JsonResult DeleteLevel(int pkId)
        {
            new LevelColorMgr().DeleteLevel(pkId, BaseEnv.UserId);

            return Json(new ResultJson<object>());
        }

        #endregion

        #region 颜色配置

        /// <summary>
        /// 颜色列表
        /// </summary>
        public ActionResult ColorIndex()
        {
            return View();
        }

        /// <summary>
        /// 查询颜色分页
        /// </summary>
        public JsonResult QueryColors(int page, int limit, ColorType? colorType)
        {
            var result = new LevelColorMgr().QueryColors(page, limit, colorType);

            return Json(new ResultJson<List<VColorSet>>(result.Item1, result.Item2));
        }

        /// <summary>
        /// 保存颜色
        /// </summary>
        public JsonResult SaveColor(ColorSet model)
        {
            if (model.PkId == 0)
            {
                model.CreateBy = BaseEnv.UserId;
                model.CreateTime = DateTime.Now;

                new LevelColorMgr().AddColor(model);
            }
            else
            {
                model.ModifyBy = BaseEnv.UserId;
                model.ModifyTime = DateTime.Now;

                new LevelColorMgr().EditColor(model);
            }

            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 删除颜色
        /// </summary>
        public JsonResult DeleteColor(int pkId)
        {
            new LevelColorMgr().DeleteColor(pkId, BaseEnv.UserId);

            return Json(new ResultJson<object>());
        }
        #endregion

        #region 颜色匹配
        /// <summary>
        /// 工单的电池片和组件颜色匹配
        /// </summary>
        public ActionResult ColorMatch(string orderNo, string workOrderNo)
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            ViewBag.Colors = new ColorMgr().QueryColors(null);
            return View();
        }

        /// <summary>
        /// 查询工单颜色匹配
        /// </summary>     
        [HttpPost]
        public JsonResult QueryWorkOrderColors(string orderNo, string workOrderNo)
        {
            var matches = new LevelColorMgr().QueryColorMatches(orderNo, workOrderNo);
            return Json(new ResultJson<object>(matches));
        }

        /// <summary>
        /// 添加颜色匹配
        /// </summary>     
        [HttpPost]
        public JsonResult AddColorMatch(VColorMatch model)
        {
            model.CreateBy = BaseEnv.UserId;
            new LevelColorMgr().AddColorMatch(model);
            return Json(new ResultJson<object>());
        }

        /// <summary>
        /// 添加颜色匹配
        /// </summary>     
        [HttpPost]
        public JsonResult RemoveColorMatch(VColorMatch model)
        {
            model.ModifyBy = BaseEnv.UserId;
            new LevelColorMgr().RemoveColorMatch(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 分拣规则配置
        /// <summary>
        /// 分拣规则管理
        /// </summary>
        public ActionResult SortRuleMgr()
        {
            var workshops = new WorkshopMgr().QueryUserWorkshops(BaseEnv.UserId);
            var machines = workshops.SelectMany(_ => new MachineMgr().QueryWorkshopMachines(_.WorkshopCode, MachineType.Sort)).ToList();

            ViewBag.Workshops = workshops;
            ViewBag.Machines = machines;
            return View();
        }

        /// <summary>
        /// 查询有效规则
        /// </summary>
        [HttpPost]
        public JsonResult QueryValidRules(string workshopCode, int machineId)
        {
            var rules = new SortMgr().QueryDisplayValidRules(workshopCode, machineId);
            return Json(new ResultJson<object>(rules));
        }

        /// <summary>
        /// 分拣规则配置
        /// </summary>
        public ActionResult SortRuleEdit(string workshopCode, int machineId)
        {
            var commonMgr = new CommonMgr();
            ViewBag.WorkshopCode = workshopCode;
            ViewBag.Machine = new MachineMgr().GetMachine(machineId);
            var rules = new SortMgr().QueryValidRules(workshopCode, machineId);
            var badReasons = new BadReasonMgr().QueryReasons(JudgeType.FinalInspection);
            rules.ForEach(rule =>
            {
                for (var i = rule.BadReasons.Count - 1; i >= 0; i--)
                {
                    var badReason = badReasons.FirstOrDefault(_ => string.Equals(_.ReasonCode, rule.BadReasons[i], StringComparison.CurrentCultureIgnoreCase));
                    if (badReason == null)
                    {
                        rule.BadReasons.RemoveAt(i);
                        continue;
                    }
                    rule.BadReasons[i] = $"{badReason.ReasonCode}-{badReason.ReasonCN}";
                }
            });
            ViewBag.Rules = rules;
            var powers = commonMgr.QueryPowers(workshopCode);
            ViewBag.Selections = new Dictionary<string, List<string>>
            {
                { "NameplateModels", powers.Select(_=>_.NameplateModel).Distinct().OrderBy(_=>_).ToList() },
                { "PowerLevels", powers.Select(_=>_.Power.ToString("0")).Distinct().OrderBy(_=>_).ToList() },
                { "CurrentLevels", commonMgr.QueryCurrents(workshopCode).Select(_=>_.LevelName.ToUpper()).Distinct().ToList() },
                { "QLevels", new LevelColorMgr().QueryLevels().Select(_=>_.Level).ToList() },
                { "ComponentColors", new LevelColorMgr().QueryColors(1,0,ColorType.ComponentColor).Item1.Select(_=>_.Color).ToList() },
                { "JunBoxSpecses", new AllocateOrderMgr().QueryFactoriesOrSpecses("接线盒",0) },
                { "JunBoxFactories", new AllocateOrderMgr().QueryFactoriesOrSpecses("接线盒",1)  },
                { "BackPlanSpecses", new AllocateOrderMgr().QueryFactoriesOrSpecses("背板",0)  },
                { "BackPlanFactories",new AllocateOrderMgr().QueryFactoriesOrSpecses("背板",1)  },
                { "AluFrameSpecses", new AllocateOrderMgr().QueryFactoriesOrSpecses("铝框",0)  },
                { "AluFrameFactories", new AllocateOrderMgr().QueryFactoriesOrSpecses("铝框",1)  },
                { "BatterySpecses", new AllocateOrderMgr().QueryFactoriesOrSpecses("电池片",0)  },
                { "BatteryFactories", new AllocateOrderMgr().QueryFactoriesOrSpecses("电池片",1)  },
                { "BadReasons", badReasons.Select(_=>$"{_.ReasonCode}-{_.ReasonCN}").ToList()  },
            };
            return View();
        }

        /// <summary>
        /// 保存分拣规则
        /// </summary>
        [HttpPost]
        public JsonResult SaveSortRules(string workshopCode, int machineId, List<VSortRule> rules)
        {
            new SortMgr().SaveRules(workshopCode, machineId, BaseEnv.UserId, rules);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 护脚机配置
        /// <summary>
        /// 包护脚机配置
        /// </summary>
        public ActionResult FootProtectMgr(string orderNo = "", string workOrderNo = "")
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            var config = new SortMgr().GetFootProtect(orderNo, workOrderNo);
            return View(config);
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public JsonResult SaveFootProtech(VFootProtectConfig model)
        {
            model.CreateBy = BaseEnv.UserId;
            new SortMgr().SaveFootProtech(model);
            return Json(new ResultJson<object>());
        }
        #endregion

        #region 物料完整性校验
        /// <summary>
        /// 物料完整性校验配置页面
        /// </summary>
        public ActionResult MaterialInfoControl(string orderNo = "", string workOrderNo = "")
        {
            ViewBag.OrderNo = orderNo;
            ViewBag.WorkOrderNo = workOrderNo;
            var config = new ViaSiteConfigMgr().GetConfig(orderNo, workOrderNo);
            return View(config);
        }

        /// <summary>
        /// 保存物料完整性校验配置
        /// </summary>
        public JsonResult SaveMaterialInfoControl(VViaSiteConfig model)
        {
            model.CreateBy = BaseEnv.UserId;
            new ViaSiteConfigMgr().SaveMaterialInfoControl(model);
            return Json(new ResultJson<object>());
        }
        #endregion
    }
}
